package com.jcroke.PC32.basetransform;

import java.lang.reflect.Constructor;

import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.traverse.TopologicalOrderIterator;

import com.jcroke.DACGraph.Pnode;
import com.jcroke.DACGraph.RDFData;
import com.jcroke.PC32.memory.Umem;
import com.jcroke.PC32.serialize.DefaultRecord;
import com.jcroke.PC32.serialize.Record;

/**
 * 
 * @author jcroke
 * 
 */
public class TransformSeqFactory {

	private RDFData _rdf;
	private Record _record;
	private FunctionalContainer _fCon;

	public TransformSeqFactory(RDFData rdf) {
		this._rdf = rdf;
		this._record = new DefaultRecord(new Umem());
		this._fCon = new FunctionalContainer(_record);
	}

	public FunctionalContainer createTFSList() throws ClassNotFoundException {

		Functional f = null;
		TopologicalOrderIterator<Pnode, DefaultEdge> rdfI = _rdf.getIterator();

		while (rdfI.hasNext()) {
			Pnode p = rdfI.next();
			f = createFunctional(p, Transformer.class);
			System.out.println("[Factory] " + "PNODE: " + p.getNodeName() + " INSTANTIATED: " + f.toString());
			f.setMemoryObject(_record);
			_fCon.add(p, f);
		}
		
		// create iterator
		_fCon.reset();
		return _fCon;
	}

	protected <T> T createFunctional(Pnode p, Class<T> ifaceClass)
			throws ClassNotFoundException {
		Class<? extends T> clazz = Class.forName(
				Pnode.substrIRI(p.getLogic().getSourceRDFClass())).asSubclass(
				ifaceClass);
		return createFunctionalInstance(clazz);
	}

	protected <T> T createFunctionalInstance(final Class<T> classToCreate) {
		final Constructor<T> constructor;
		T result = null;
		try {
			constructor = classToCreate.getDeclaredConstructor();
			result = constructor.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}